﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Collections;
using System.Web;
using Solution.Business;
using Solution.Data;

namespace Solution.Business.Infrastructure
{

    //  [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
    public class CAuthorizeAttribute : AuthorizeAttribute
    {
        public CAuthorizeAttribute(AuthorizationContext filterContext)
        {
        }
        public CAuthorizeAttribute()
        {
        }
        public string Module { get; set; }
        /// <summary>
        /// V view, I insert, D delete, U update, A All split by ,
        /// </summary>
        public string Functions { get; set; }
        public string Mess { get; set; }
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);

            var UserName = filterContext.HttpContext.User.Identity.Name;
            if (UserName == null)
                CloseConnection(filterContext);
            else
            {
                User _User = new UserBLL().GetOne(UserName);
                UserData _UserData = new UserData(_User.Id, _User.LoginName);
                var isAuthorized = false;
                HttpSessionStateBase session = filterContext.HttpContext.Session;
                isAuthorized = CAuthen.IsTrueAuthenFun(_UserData, Module, Functions);
                if (!isAuthorized)
                    CloseConnection(filterContext);
            }

        }

        /// <summary>
        /// Closes the connection and sets the status code to Unauthorized
        /// </summary>
        /// <param name="filterContext">The AuthorizationContext</param>
        private void CloseConnection(AuthorizationContext filterContext)
        {
            HttpResponseBase response = filterContext.HttpContext.Response;
            response.Redirect("~/Admin/Success/NotAuthorized");
            //response.StatusCode = 401;//Unauthorized status code
            //if (string.IsNullOrEmpty(Mess))
            //    Mess = "You are not authorized! <a href=\"javascript: window.history.go(-1)\">Go Back pages</a>";
            //response.Write(Mess);
            //response.Flush();
            //response.Close();
            response.End();
        }

    }
}
